package top.fullj.eventbus;

import java.lang.reflect.Method;

/**
 * @author bruce.wu
 * @since 2023/8/7 14:07
 */
public final class EventBusPlugins {

    private static volatile ErrorHandler errorHandler;

    private static volatile OnExecuteAssembly onExecuteAssembly;

    public static void setErrorHandler(ErrorHandler handler) {
        errorHandler = handler;
    }

    public static void setOnExecuteAssembly(OnExecuteAssembly assembly) {
        onExecuteAssembly = assembly;
    }

    static void onError(EventBus bus, Object event, Object subscriber, Method method, Throwable tr) {
        ErrorHandler f = errorHandler;
        if (f == null) {
            Throwable cause = tr.getCause() == null ? tr : tr.getCause();
            cause.printStackTrace();
        } else {
            f.onError(bus, event, subscriber, method, tr);
        }
    }

    static Runnable onExecute(Runnable r) {
        OnExecuteAssembly f = onExecuteAssembly;
        if (f == null) {
            return r;
        }
        return f.apply(r);
    }

    private EventBusPlugins() {
        throw new IllegalStateException();
    }

}
